package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Method;
import java.util.*;

@Controller
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private ApplicationContext ctx;

    @RequestMapping("/list")
    @RequiredPermission(name = "权限查询", expression = "permission:list")
    public String list(Model model, QueryObject qo) {
        PageInfo<Permission> pageInfo = permissionService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "permission/list";
    }

    @RequestMapping("/reload")
    @RequiredPermission(name = "权限加载", expression = "permission:reload")
    @ResponseBody
    public JsonResult reload() {
        //        int i= 1/0;

            Set<Permission> permissions = new LinkedHashSet<>();
            List<Permission> allPermissions = permissionService.listAll();
            ArrayList<String> expressions = new ArrayList<>();
            for (Permission permission : allPermissions) {
                expressions.add(permission.getExpression());
            }


            Map<String, Object> beans = ctx.getBeansWithAnnotation(Controller.class);
            Collection<Object> controllers = beans.values();
            for (Object controller : controllers) {
                Method[] methods = controller.getClass().getDeclaredMethods();
                for (Method method : methods) {
                    Permission permission = new Permission();
                    RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
                    permission.setName(annotation.name());
                    permission.setExpression(annotation.expression());
                    if (!expressions.contains(annotation.expression())) {
                        permissions.add(permission);
                    }
                }
            }
            if (permissions.size()>0){
                permissionService.save(permissions);
            }
            return new JsonResult(true,"加载成功");







    }
    @RequestMapping("/noPermission")
    public String noPermission(){
        return "common/nopermission";
    }

}
